<template>
  <div id="BookManage">
    <div id="head">
      <ul>
        <li>
          <el-button type="primary" @click="adddata">添加<i class="el-icon-circle-plus"/></el-button>
        </li>
        <li>查询条件：</li>
        <li>
          <el-select v-model="value" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </li>
        <li>
          <span> 搜索： </span>
        </li>
        <li @keyup.enter="searchBook">
          <el-input placeholder="请输入关键字" v-model:value="searchValue"></el-input>
        </li>
        <li>
          <el-button type="primary" @click="searchBook">查询</el-button>
        </li>
      </ul>
    </div>
    <div id="main">
      <el-empty description="请检索" v-show="false"></el-empty>
      <div id="sort">
        <ul>
          <li>期刊编号</li>
          <li>期刊名称</li>
          <li>出版日期</li>
          <li>在库数量</li>
          <li>借阅情况</li>
          <li>所属类别</li>
          <li>操作</li>
        </ul>
      </div>
      <div id="detail">
        <ul v-for="(item,index) in libs">
          <li><input :disabled="true" v-model:onfocusout="libs[index].mid"></li>
          <li><input :disabled="editAble[index]" v-model:onfocusout="libs[index].name"></li>
          <li><input :disabled="editAble[index]" v-model:onfocusout="libs[index].publishDate"></li>
          <li><input :disabled="editAble[index]" v-model:onfocusout="libs[index].amount"></li>
          <li><input :disabled="editAble[index]" v-model:onfocusout="libs[index].borrowstate"></li>
          <li><input :disabled="editAble[index]" v-model:onfocusout="libs[index].classify"></li>
          <li>
            <el-button id="amend" type="primary" v-show="editAble[index]" @click="amending(index)">修改</el-button>
            <el-button id="save" type="primary" v-show="showSaved[index]" @click="saving(index)">保存</el-button>
            <el-button id="delete" type="primary" @click="deleting(index)">删除</el-button>
          </li>
        </ul>
      </div>
    </div>
    <div id="bottom">
      <ul>
        <li>
          <el-button type="primary" @click="homepage">首页</el-button>
        </li>
        <li>
          <el-button @click="lastpage">上一页</el-button>
        </li>
        <li>第{{ nowPage }}/{{ totalPage }}页</li>
        <li>
          <el-button @click="nextpage">下一页</el-button>
        </li>
        <li>
          <el-button type="primary" @click="trailerpage">尾页</el-button>
        </li>
        <li>当前页共{{ this.libs.length }}条数据</li>
      </ul>
    </div>
  </div>
</template>

<!--随意的给数组赋值数组，在vue中赋值大多数时候都是引用其地址，会造成同一变量的结果，注意-->
<script>
import axios from "axios";

export default {
  name: "MagazineManage",
  data() {
    return { //使用return包裹的变量只在当前组件中生效
      libs: [],
      libsSearch: [],//搜索数组
      searchValue: "",
      libsDatabase: [],//总数组
      transitDatabase:[],//中转数组
      nowPage: 1,
      totalPage: 1,
      showSaved: [false, false, false, false, false, false, false, false],
      editAble: [true, true, true, true, true, true, true, true],
      saveMode: 'amend',
      options: [
        {
          value: 'mid',
          label: '期刊编号'
        },{
          value: 'name',
          label: '期刊名称'
        },{
          value: 'publishDate',
          label: '出版日期'
        },{
          value: 'amount',
          label: '期刊数量'
        },{
          value: 'borrowstate',
          label: '期刊借阅情况'
        },{
          value: 'classify',
          label: '期刊分类'
        },],
      value: 'name'
    }
  },
  methods: {

    searchBook() {
      if (this.searchValue !== "") {
        this.libsSearch = []; //清空搜索存储数组
        for (let i = 0; i < this.libsDatabase.length; i++) {
          switch (this.value) {
            case "mid":
              if (this.libsDatabase[i].mid === this.searchValue) {
                this.libsSearch.push(this.libsDatabase[i]);
              }
              break;
            case "name":  //调用函数，通过关键字查找匹配项
              if (this.strMatch(this.libsDatabase[i].name, this.searchValue) === true) {
                this.libsSearch.push(this.libsDatabase[i]);
              }
              break;
            case "publishDate"://调用函数，通过关键字查找匹配项
              if (this.strMatch(this.libsDatabase[i].publishDate, this.searchValue) === true) {
                this.libsSearch.push(this.libsDatabase[i]);
              }
              break;
            case "amount":
              if (this.libsDatabase[i].amount === parseInt(this.searchValue)) {
                this.libsSearch.push(this.libsDatabase[i]);
              }
              break;
            case "borrowstate":
              if (this.libsDatabase[i].borrowstate === this.searchValue) {
                this.libsSearch.push(this.libsDatabase[i]);
              }
              break;
            case "classify"://调用函数，通过关键字查找匹配项
              if (this.strMatch(this.libsDatabase[i].classify, this.searchValue) === true) {
                this.libsSearch.push(this.libsDatabase[i]);
              }
              break;
          }
        }
        ;

      }this.showData();
    },

    strMatch(str, key) {// 模糊匹配
      let newkey = key.split(/\s/g);//切割空格关键字
      for (let i = 0; i < newkey.length; i++) {
        if (str.match(newkey[i]) != null) {
          return true //match检索到目标字段，返回true
        }
      }
      return false
    },

    showData() {
      if (this.searchValue !== "") {
        this.libsDatabase = this.libsSearch;
        this.initalize();
      } else {
        this.linkDatabase();
      }
    },


    adddata() {//添加一排表格
      if (this.libs.length < 8) { //于当前页面有空余时，添加表格
        if (this.editAble[this.libs.length - 1] !== false) {
          //计算出下一位“Mxxxx”mid
          let midNum = parseInt(this.libs[this.libs.length - 1].mid.slice(-4)) + 1; //获取mid中的含0纯数字部分
          let midNumLen = midNum.toString().length;//获取mid中的纯数字部分的长度
          let midNew;//新的mid
          switch (midNumLen) {
            case 1:
              midNew = "M000" + midNum.toString();
              break;
            case 2:
              midNew = "M00" + midNum.toString();
              break;
            case 3:
              midNew = "M0" + midNum.toString();
              break;
            case 4:
              midNew = "M" + midNum.toString();
              break;
          }
          this.libs.push({
            mid: midNew,
            name: "",
            publishDate: "",
            amount: 0,
            borrowstate: "在馆",
            classify: "",
          });
          this.libsDatabase.push(this.libs[this.libs.length - 1]);
          this.saveMode = "insert";
          this.editAble[this.libs.length - 1] = false;
          this.showSaved[this.libs.length - 1] = true;
        }
      } else if (this.libs.length === 8) {//当前页面无空余时，添加表格
        if ((this.totalPage - this.nowPage) >= 1) { //当前页距离尾页超过一页
          this.trailerpage();//跳转尾页
          this.adddata();//回调自身,添加数据
        } else if ((this.totalPage - this.nowPage) === 0) { //当前页是尾页
          this.libs = [];//清空页面数组
          this.totalPage++;
          this.nowPage++;
          this.adddata();
        }
      }
    },
    // 修改（可编辑状态）
    amending(index) {
      this.editAble[index] = false;
      this.showSaved[index] = true;
      this.saveMode = "amend";
      this.$forceUpdate(); //解决修改属性数据后，页面不刷新的问题，通过强制刷新解决
    },
    // 保存（关闭可编辑状态）
    saving(index) {
      let that=this;
      if (this.libs[index].name === "" || this.libs[index].publishDate === "" || this.libs[index].classify === "") { //检测书名、出版社、分类是否为空值，数量与借阅状态在上面已先行判断了
        this.$message({
          message: '请输入相对应的值',
          type: 'warning'
        });
      } else {
        this.editAble[index] = true;
        this.showSaved[index] = false;
        if (this.saveMode === "amend") {
          axios({    //修改数据
            method: 'post',
            url: 'http://localhost:3000/magazineManage/amend',
            params: {
              mid: this.libs[index].mid,
              name: this.libs[index].name,
              publishDate: this.libs[index].publishDate,
              amount: this.libs[index].amount,
              borrowstate: this.libs[index].borrowstate,
              classify: this.libs[index].classify,
            },
            data: {},
            //使用post一定要写，为何请求报文一定要规定的头，其原因不详
            //推测可能是浏览器或者服务端node的原因
            headers: {'content-Type': 'application/x-www-form-urlencoded'},
          }).then(function (response) {
            console.log(response)
          }).catch(function (error) {
            console.log(error);
          });
        } else {    //插入新数据
          axios({
            method: 'post',
            url: 'http://localhost:3000/magazineManage/insert',
            params: {
              mid: this.libs[index].mid,
              name: this.libs[index].name,
              publishDate: this.libs[index].publishDate,
              amount: this.libs[index].amount,
              borrowstate: this.libs[index].borrowstate,
              classify: this.libs[index].classify,
            },
            data: {},
            //使用post一定要写，为何请求报文一定要规定的头，其原因不详
            //推测可能是浏览器或者服务端node的原因
            headers: {'content-Type': 'application/x-www-form-urlencoded'},
          }).then(function (response) {
            console.log(response.data);
            if (response.data === "success!") {
              that.$message({
                message: '添加数据成功',
                type: 'success'
              });
            }
          }).catch(function (error) {
            console.log(error);
          });
        }
        this.$forceUpdate();
      }
    },
    // 删除
    deleting(index) {
      //删除数据库的数据
      let that=this;
      let deletedMid = this.libs[index].mid;
      axios({
        method: 'post',
        url: 'http://localhost:3000/magazineManage/delete',
        params: {
          mid: this.libs[index].mid,
        },
        data: {},
        //使用post一定要写，为何请求报文一定要规定的头，其原因不详
        //推测可能是浏览器或者服务端node的原因
        headers: {'content-Type': 'application/x-www-form-urlencoded'},
      }).then(function (response) {
        console.log(response.data);
        if (response.data === "success!") {
          that.$message({
            message: "删除" + deletedMid + "号数据成功",
            type: 'success'
          });
        }
      }).catch(function (error) {
        console.log(error);
      });

      //index是从0开始的
      if (index === 0) {//是第一条数据时
        this.libs.shift();
        this.libsDatabase.splice((this.nowPage - 1) * 8 + index, 1);
      } else if (index + 1 === this.libs.length) {//最后一条数据时
        this.libs.pop();
        this.libsDatabase.splice((this.nowPage - 1) * 8 + index, 1);
      } else {//中间数据
        this.libs.splice(index, 1);
        this.libsDatabase.splice((this.nowPage - 1) * 8 + index, 1);
      }
      if (this.libs.length === 0) {//没有数据时
        this.lastpage();
      }
    },
    // 上一页
    lastpage() {
      if (this.nowPage > 1) {//限制措施，防止第一页跳负页
        for (let i = 0; i < 8; i++) {
          this.libs[i] = this.libsDatabase[(this.nowPage - 2) * 8 + i];
        }
        this.nowPage--;
        this.$forceUpdate();//强制刷新页面
      }
    },
    // 下一页
    nextpage() {
      if (this.nowPage < this.totalPage) {//限制措施，防止尾页跳溢出页
        this.libs = [];//清空
        if ((this.totalPage - this.nowPage) > 1) { //满8条数据的下一页
          for (let i = 0; i < 8; i++) {
            this.libs[i] = this.libsDatabase[this.nowPage * 8 + i];//把数据写入到当前页面数组
          }
        } else if (this.totalPage - this.nowPage === 1) {//不满8条数据的下一页
          for (let i = 0; i < this.libsDatabase.length % 8; i++) {
            this.libs[i] = this.libsDatabase[this.nowPage * 8 + i];
          }
        }
        this.nowPage++;
        this.$forceUpdate();
      }
    },
    //首页
    homepage() {
      if (this.nowPage > 1) {
        for (let i = 0; i < 8; i++) {
          this.libs[i] = this.libsDatabase[i];
        }
        this.nowPage = 1;
        this.$forceUpdate();
      }
    },
    // 尾页
    trailerpage() {
      if (this.nowPage < this.totalPage) {
        this.libs = [];
        if ((this.libsDatabase.length % 8) !== 0) {//不满8条数据
          for (let i = 0; i < this.libsDatabase.length % 8; i++) {
            this.libs[i] = this.libsDatabase[(this.totalPage - 1) * 8 + i];
          }
        } else {
          for (let i = 0; i < 8; i++) {//满8条数据
            this.libs[i] = this.libsDatabase[this.nowPage * 8 + i];
          }
        }
        this.nowPage = this.totalPage;
        this.$forceUpdate();
      }
    },
    initalize(){//初始话数据界面
      this.libs=[];
      if (this.libsDatabase.length >= 8) {
        for (let i = 0; i < 8; i++) {   //把第一面的数据写入
          this.libs.push(this.libsDatabase[i])
        }//此时在libdatabase中，所有的数据已经在了，所以只要更改页数就可以了
        this.totalPage = parseInt(this.libsDatabase.length / 8) + 1;
        this.nowPage = 1;
      }else{
        for (let i = 0; i < this.libsDatabase.length; i++) {   //把第一面的数据写入
          this.libs.push(this.libsDatabase[i])
        }
      }
    },
    // -----------------------------从数据库接入数据--------------------------
    linkDatabase() {
      this.libsDatabase=[];
      axios.get('http://localhost:3000/magazineManage/get').then((response) => {
        let that = this.libsDatabase;
        response.data.forEach(function (value, index) {
          that.push(response.data[index]);
        })
        this.initalize();
      })
    }
    // -----------------------------从数据库接入数据--------------------------
  },
  created() {
    this.linkDatabase();//连接数据库初始化
  }
}
</script>

<style>
@import '../../assets/css/BookManage.css';
</style>